package cn.walls1717.wallsmall.seckill.config;

import cn.walls1717.wallsmall.common.utils.R;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.walls1717.wallsmall.common.exception.BizCodeEnum.TOO_MANY_REQUEST_EXCEPTION;

/**
 * @author walls1717
 * @since 2022/11/28 13:56
 **/
@Component
public class SentinelUrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {

        R r = R.error(TOO_MANY_REQUEST_EXCEPTION.getCode(), TOO_MANY_REQUEST_EXCEPTION.getMsg());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().write(JSON.toJSONString(r));
    }
}
